// 1. React核心库
import React, { useState, useEffect, useCallback } from 'react';

// 2. UI组件库
import { Card, Row, Col, Statistic, List, Avatar, Tag, Spin } from 'antd';

// 3. 图标库
import { UserOutlined, TeamOutlined, CrownOutlined, ClockCircleOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 工具库
import { useModel, useAccess } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import PermissionDebugger from '@/components/PermissionDebugger';

// 7. 生成的类型定义
import type { UserProfile } from '@/services/generated/src';

interface DashboardStats {
  totalUsers: number;
  activeUsers: number;
  adminUsers: number;
  recentUsers: UserProfile[];
}

const HomePage: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const access = useAccess();
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    activeUsers: 0,
    adminUsers: 0,
    recentUsers: [],
  });
  const [statsLoading, setStatsLoading] = useState(false);

  // 获取仪表板统计数据
  const fetchStats = useCallback(async () => {
    try {
      setStatsLoading(true);
      await autoLoginInDev();

      // 获取用户列表统计
      const response = await apiClients.users.usersList({
        page: 1,
        pageSize: 10,
      });

      console.log('🚀 首页统计API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const responseData = (response as any).data || response;
      const users = responseData?.items || [];
      const total = responseData?.total || 0;

      const activeCount = users.filter((user: any) => user.is_active).length;
      const adminCount = users.filter((user: any) => user.is_staff).length;

      setStats({
        totalUsers: total,
        activeUsers: activeCount,
        adminUsers: adminCount,
        recentUsers: users.slice(0, 5),
      });
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setStatsLoading(false);
    }
  }, []);

  // 初始化数据获取
  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  return (
    <PageContainer
      title={`欢迎回来，${currentUser?.first_name || currentUser?.username || '用户'}！`}
      subTitle="用户管理系统仪表板"
    >
      <Spin spinning={statsLoading}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="总用户数"
                value={stats.totalUsers}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="活跃用户"
                value={stats.activeUsers}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="管理员"
                value={stats.adminUsers}
                prefix={<CrownOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="最近登录"
                value={stats.recentUsers.length}
                prefix={<ClockCircleOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          <Col xs={24} lg={12}>
            <Card title="最近注册用户" size="small">
              <List
                itemLayout="horizontal"
                dataSource={stats.recentUsers}
                renderItem={(user) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<Avatar icon={<UserOutlined />} />}
                      title={user.username}
                      description={
                        <div>
                          <div>{user.email}</div>
                          <div>
                            <Tag color={user.is_active ? 'green' : 'red'}>
                              {user.is_active ? '激活' : '禁用'}
                            </Tag>
                            {user.is_staff && <Tag color="gold">管理员</Tag>}
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="系统信息" size="small">
              <List size="small">
                <List.Item>
                  <List.Item.Meta
                    title="当前用户"
                    description={currentUser?.username || '未登录'}
                  />
                </List.Item>
                <List.Item>
                  <List.Item.Meta
                    title="用户权限"
                    description={
                      <div>
                        {currentUser?.is_superuser && (
                          <Tag color="purple" icon={<CrownOutlined />}>超级用户</Tag>
                        )}
                        <Tag color={currentUser?.is_staff ? 'gold' : 'blue'}>
                          {currentUser?.is_staff ? '管理员' : '普通用户'}
                        </Tag>
                      </div>
                    }
                  />
                </List.Item>
                <List.Item>
                  <List.Item.Meta
                    title="账户状态"
                    description={
                      <Tag color={currentUser?.is_active ? 'green' : 'red'}>
                        {currentUser?.is_active ? '激活' : '禁用'}
                      </Tag>
                    }
                  />
                </List.Item>
                <List.Item>
                  <List.Item.Meta
                    title="权限说明"
                    description={
                      currentUser?.is_superuser ? (
                        <Tag color="purple">🎉 拥有所有权限</Tag>
                      ) : (
                        <Tag color="default">基于权限和组控制</Tag>
                      )
                    }
                  />
                </List.Item>
              </List>
            </Card>
          </Col>
        </Row>

        {/* 权限测试面板 */}
        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          <Col span={24}>
            <Card title="🔐 权限测试面板" size="small">
              <Row gutter={[8, 8]}>
                <Col span={6}>
                  <Tag color={access.canViewUsers ? 'green' : 'red'}>
                    {access.canViewUsers ? '✅' : '❌'} 查看用户
                  </Tag>
                </Col>
                <Col span={6}>
                  <Tag color={access.canCreateUser ? 'green' : 'red'}>
                    {access.canCreateUser ? '✅' : '❌'} 创建用户
                  </Tag>
                </Col>
                <Col span={6}>
                  <Tag color={access.canViewGroups ? 'green' : 'red'}>
                    {access.canViewGroups ? '✅' : '❌'} 查看组
                  </Tag>
                </Col>
                <Col span={6}>
                  <Tag color={access.canViewPermissions ? 'green' : 'red'}>
                    {access.canViewPermissions ? '✅' : '❌'} 查看权限
                  </Tag>
                </Col>
              </Row>
              <div style={{ marginTop: 8, fontSize: '12px', color: '#666' }}>
                {currentUser?.is_superuser ?
                  '🎉 超级用户自动拥有所有权限' :
                  '权限基于用户组和直接分配的权限'
                }
              </div>
            </Card>
          </Col>
        </Row>

        {/* 权限调试信息 - 仅在开发环境显示 */}
        {process.env.NODE_ENV === 'development' && (
          <Row style={{ marginTop: 16 }}>
            <Col span={24}>
              <PermissionDebugger />
            </Col>
          </Row>
        )}
      </Spin>
    </PageContainer>
  );
};

export default HomePage;
